﻿using System;
using System.Data;
using System.Data.Common;
using System.Collections.Generic;
using System.Text;

namespace mfe.lib.data
{
    /// <summary>
    /// This takes in a database provider and return a generic <see cref="Database"/> object.
    /// </summary>
    public class DatabaseFactory
    {

        /// <summary>
        /// Creates the database.
        /// </summary>
        /// <returns></returns>
        public static Database CreateDatabase()
        {
            return CreateDatabase(string.Empty);
        }

        public static Database CreateDatabase(string name)
        {
            System.Configuration.ConnectionStringSettingsCollection connstrs = System.Configuration.ConfigurationManager.ConnectionStrings;
            string defaultDatabase = System.Configuration.ConfigurationManager.AppSettings["defaultDatabase"];
            string variant = string.Empty;
            if (name.Length > 0)
                variant = connstrs[name].ProviderName;
            else
                variant = connstrs[defaultDatabase].ProviderName;


            DbProviderFactory factory = DbProviderFactories.GetFactory(variant);
            Database db = new Database();
            SetParameterToken(connstrs[defaultDatabase].ProviderName, db);
            db.DbProviderFactory = factory;
            db.DbConnection = factory.CreateConnection();
            db.DbConnection.ConnectionString = connstrs[defaultDatabase].ConnectionString;

            return db;
        }

        private static void SetParameterToken(string provider, Database db)
        {
            switch (provider)
            {
                case "MySql.Data.MySqlClient":
                    db.ParameterToken = '?';
                    break;
                case "System.Data.SqlClient":
                case "IBM.Data.DB2":
                    db.ParameterToken = '@';
                    break;
                default:
                    db.ParameterToken = '@';
                    break;
            }
        }
    }
}
